App.controller('empController', ['$rootScope', '$scope', '$state', 'Page', 'XCode', function($rootScope, $scope, $state, Page, XCode) {

	// 初始化部门树
    Page.ajaxPost("department/tree.do", null, function (response) {
		$scope.depts = response.data;

		if (response.data.length > 0) {
			response.data[0].open = true;// 根节点展开
			// 左边部门岗位树
			$scope.deptTree = $.fn.zTree.init($("#deptTree"), {
				check: {
					enable: false
				},
				data: {
					simpleData: {
						enable: true,
						idKey: "deptId",
						pIdKey: "parentDeptId"
					},
					key: {
						name: "deptName"
					}
				},
				callback: {
					onClick: function(event, treeId, treeNode, clickFlag) {
						$scope.$apply(function() {
							$scope.dept = treeNode;
							$scope.empGrid.query({deptId: treeNode.deptId});
						});
					}
				}
			}, response.data);
		}
    });

	$scope.empGrid = {
		column_defs: [
			{
				target: 5,
				template: function(row) {
					var template = '';
					$(row.poses).each(function(i, pos) {
						if (i > 0) {
							template += '<br>'
						}
						template += XCode.getName('pos', pos.posId) + '-' + pos.deptName;
					});
					return template;
				}
			}
		],
		add : function () {
			$scope.empGrid._add = true;
			$scope.empGrid.edit = true;
			$scope.emp = {poses: [{}]};
		},
		update: function(row) {
			$scope.empGrid._add = false;
			$scope.empGrid.edit = true;
			$scope.emp = row;
		},
		save: function() {
			var flag = true;
			$($scope.emp.poses).each(function(i, pos) {
				if (!(pos.deptId && pos.posId)) {
					flag = false;
					return false;
				}
			});
			if (!flag) {
				Page.alert('请选择部门和岗位！');
				return false;
			}
			Page.ajaxPost($scope.empGrid._add ? 'emp/add.do' : 'emp/update.do', $scope.emp, function() {
				$scope.empGrid.edit = false;
				$scope.empGrid.query();
				$scope.emp = {};
			});
		}
	};

	$scope.addPos = function() {
		if (!$scope.emp.poses) {
			$scope.emp.poses = [];
		}
		$scope.emp.poses.push({});
	}

	$scope.deletePos = function(index) {
		$scope.emp.poses.splice(index, 1);
	}
}]);